package com.ygqh.baby.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.ProductStatus;
import com.ygqh.baby.ao.PromotionType;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.mapper.YgActivityGiveawayMapper;
import com.ygqh.baby.model.ActivityGiveawayModel;
import com.ygqh.baby.po.YgActivityGiveaway;
import com.ygqh.baby.po.YgActivityGiveawayExample;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgProductImages;
import com.ygqh.baby.po.YgSku;
import com.ygqh.baby.po.YgStock;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgActivityGiveawayService;
import com.ygqh.baby.service.YgProductImagesService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgSkuService;
import com.ygqh.baby.service.YgStockService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.JsonUtils;

@Service
public class YgActivityGiveawayServiceImpl implements YgActivityGiveawayService {

	@Autowired
	private YgActivityGiveawayMapper ygActivityGiveawayMapper;

	@Autowired
	private RedisDao redisDao;

	@Autowired
	private YgSkuService skuService;

	@Autowired
	private YgProductService productService;

	@Autowired
	private YgStockService stockService;
	@Autowired
	private YgProductImagesService ygProductImagesService;

	@Override
	public List<YgActivityGiveaway> find() {
		YgActivityGiveawayExample example = new YgActivityGiveawayExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygActivityGiveawayMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgActivityGiveawayExample example = new YgActivityGiveawayExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygActivityGiveawayMapper.countByExample(example);
	}

	@Override
	public YgActivityGiveaway findById(Long id) {
		YgActivityGiveaway giveaway = ygActivityGiveawayMapper.selectByPrimaryKey(id);
		String key = "giveCount_" + giveaway.getSourceCode() + "_" + giveaway.getSkuCode();
		String hasGiveAmount = redisDao.get(key);
		if (StringUtil.isNotBlank(hasGiveAmount)) {
			giveaway.setHasGiveCount(Long.parseLong(hasGiveAmount));
		}
		return giveaway;
	}

	@Override
	public int save(YgActivityGiveaway ygActivityGiveaway) {
		return ygActivityGiveawayMapper.insertSelective(ygActivityGiveaway);
	}

	@Override
	public int update(YgActivityGiveaway ygActivityGiveaway) {
		return ygActivityGiveawayMapper.updateByPrimaryKeySelective(ygActivityGiveaway);
	}

	@Override
	public ResultSet<YgActivityGiveaway> search(QueryInfo queryInfo, String q, Date startDate, Date endDate,
			String pStatus) {
		List<YgActivityGiveaway> list = ygActivityGiveawayMapper.selectSuper(queryInfo, q, startDate, endDate, pStatus);
		int count = ygActivityGiveawayMapper.countSuper(q, startDate, endDate, pStatus);
		ResultSet<YgActivityGiveaway> resultSet = new ResultSet<YgActivityGiveaway>(count, list);
		return resultSet;
	}

	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		YgActivityGiveawayExample example = new YgActivityGiveawayExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		YgActivityGiveaway record = new YgActivityGiveaway();
		record.setStatus(DataStatus.Delete);

		return ygActivityGiveawayMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[] { id });
	}

	@Override
	public int saveOrUpdate(YgActivityGiveaway ygActivityGiveaway) {
		int r = 0;
		if (ygActivityGiveaway.getId() != null) {
			r = this.update(ygActivityGiveaway);
		} else {
			r = this.save(ygActivityGiveaway);
		}
		return r;
	}

	@Override
	public Message saveGiveaway(YgActivityGiveaway activityGiveaway, String handler) {
		/**
		 * 判断SKU 是否存在
		 */
		YgSku skuOrdinary = skuService.findBySkuCode(activityGiveaway.getSkuCode(), PromotionType.Ordinary);

		if (skuOrdinary == null) {
			return Message.error("101", "SKU不存在");
		}

		/**
		 * redis是否存在有效赠品
		 */
		if (setRedisGiveAway(activityGiveaway, "add")) {
			return Message.error("105", "SOURCE值已经存在没有完成活动");
		}

		/**
		 * 判断是否存在赠品
		 */
		YgSku skuManZeng = skuService.findBySkuCode(activityGiveaway.getSkuCode(), PromotionType.ManZeng);
		if (skuManZeng == null) {
			/**
			 * 增加一个新的商品
			 */
			YgProduct productOrd = productService.findDetailById(skuOrdinary.getProductId());

			YgStock stock = stockService.findBySkuCode(skuOrdinary.getSkuCode());
			if (stock == null) {
				return Message.error("102", "赠品库存已空");
			}
			if (stock.getAmount() <= 0) {
				return Message.error("103", "赠品库存已空");
			}

			if (stock.getAmount() < activityGiveaway.getGiveCount()) {
				return Message.error("104", "没有足够的赠品，现库存数：" + stock.getAmount());
			}

			this.addProduct(productOrd, handler, skuOrdinary);
		}

		// long giveawayMinutes = DateConvertUtils.diffMinutes(new Date(),
		// DateConvertUtils.getDateEnd(DateConvertUtils.addDay(activityGiveaway.getEndDate(),
		// -1)));
		activityGiveaway.setCreateBy(handler);
		activityGiveaway.setCreateTime(new Date());
		this.save(activityGiveaway);
		// redisDao.set("giveaway_"+activityGiveaway.getSourceCode(),JsonUtils.toJson(copyGiveaway(activityGiveaway))
		// , (Integer.parseInt(giveawayMinutes+"")) * 60 * 1000);

		return Message.success("0000", "添加SOURCE值赠品成功");
	}

	@Override
	public Message updateGiveaway(YgActivityGiveaway activityGiveaway, String handler) {
		/**
		 * 判断SKU 是否存在
		 */
		YgSku skuOrdinary = skuService.findBySkuCode(activityGiveaway.getSkuCode(), PromotionType.Ordinary);

		if (skuOrdinary == null) {
			return Message.error("101", "SKU不存在");
		}

		/**
		 * 判断是否存在赠品
		 */
		YgSku skuManZeng = skuService.findBySkuCode(activityGiveaway.getSkuCode(), PromotionType.ManZeng);
		if (skuManZeng == null) {
			/**
			 * 增加一个新的商品
			 */
			YgProduct productOrd = productService.findDetailById(skuOrdinary.getProductId());

			YgStock stock = stockService.findBySkuCode(skuOrdinary.getSkuCode());
			if (stock == null) {
				return Message.error("102", "赠品库存已空");
			}
			if (stock.getAmount() <= 0) {
				return Message.error("103", "赠品库存已空");
			}

			if (stock.getAmount() < activityGiveaway.getGiveCount()) {
				return Message.error("104", "商品库存不足");
			}

			this.addProduct(productOrd, handler, skuOrdinary);
		}
		long giveawayMinutes = DateConvertUtils.diffMinutes(new Date(),
				DateConvertUtils.getDateEnd(DateConvertUtils.addDay(activityGiveaway.getEndDate(), -1)));

		/**
		 * redis是否存在有效赠品
		 */
		if (setRedisGiveAway(activityGiveaway, "update")) {
			return Message.error("105", "SOURCE值已经存在没有完成活动");
		}

		/*
		 * //判断是否修改SOURCE
		 * if(!activityGiveaway.getSourceCode().equals(activityGiveaway
		 * .getOldSourceCode())){ String
		 * result=redisDao.get("giveaway_"+activityGiveaway.getSourceCode());
		 * if(!StringUtil.isEmpty(result)){ return Message.error("105",
		 * "SOURCE值已经存在没有完成活动"); } }
		 */

		activityGiveaway.setUpdateBy(handler);
		activityGiveaway.setUpdateTime(new Date());

		this.update(activityGiveaway);
		// redisDao.set("giveaway_"+activityGiveaway.getSourceCode(),JsonUtils.toJson(copyGiveaway(activityGiveaway)),
		// (Integer.parseInt(giveawayMinutes+"")) * 60 * 1000);

		return Message.success("0000", "更改SOURCE值赠品成功");
	}

	/**
	 * 保存新品与sku
	 * 
	 * @param productOrd
	 * @param handler
	 * @param skuOrdinary
	 */
	private void addProduct(YgProduct goods, String handler, YgSku skuOrdinary) {

		YgProduct product = new YgProduct();
		product.setProductCode(goods.getProductCode());
		product.setProductName(goods.getProductName());
		product.setProductOriginalPrice(goods.getProductOriginalPrice());
		product.setProductSalePrice(goods.getProductSalePrice());
		product.setProductType(goods.getProductType());
		product.setBrandId(goods.getBrandId());
		product.setGroupId(goods.getGroupId());
		product.setCategoryId(goods.getCategoryId());
		product.setSupplierId(goods.getSupplierId());
		product.setStyleId(goods.getStyleId());
		product.setUnitName(goods.getUnitName());
		product.setDetailImagePath(goods.getDetailImagePath());
		product.setShortName(goods.getShortName());
		product.setCreateTime(new Date());
		product.setCreateBy(handler);
		product.setSaleStatus(ProductStatus.OnSale);
		product.setPromotionType(PromotionType.ManZeng);

		int row = productService.save(product);

		if (goods.getYgSkus() != null) {
			List<YgSku> skuList = new ArrayList<YgSku>();

			for (YgSku ygSku : goods.getYgSkus()) {
				YgSku sku = new YgSku();
				sku.setSkuCode(ygSku.getSkuCode());
				sku.setProductId(product.getId());
				sku.setSizeName(ygSku.getSizeName());
				sku.setSalesPrice(ygSku.getSalesPrice());
				sku.setSourceSalesPrice(goods.getProductSalePrice());
				sku.setCreateTime(new Date());
				sku.setCreateBy(handler);
				skuList.add(sku);
			}

			skuService.addSkuInBatch(skuList);
		}
		if (goods.getProductImages() != null) {

			List<YgProductImages> imageList = new ArrayList<YgProductImages>();

			for (YgProductImages productImages : goods.getProductImages()) {
				YgProductImages image = new YgProductImages();
				image.setImagePath(productImages.getImagePath());
				image.setIsMain(productImages.getIsMain());
				image.setProductId(product.getId());
				image.setSortNum(productImages.getSortNum());
				imageList.add(image);
			}
			ygProductImagesService.saveBatch(imageList);
		}
	}

	public ActivityGiveawayModel copyGiveaway(YgActivityGiveaway activityGiveaway) {
		ActivityGiveawayModel agtiveModel = new ActivityGiveawayModel();
		agtiveModel.setActivityName(activityGiveaway.getActivityName());
		agtiveModel.setSourceCode(activityGiveaway.getSourceCode());
		agtiveModel.setSkuCode(activityGiveaway.getSkuCode());
		agtiveModel.setGiveCount(activityGiveaway.getGiveCount());
		agtiveModel.setPayPrice(activityGiveaway.getPayPrice());
		agtiveModel.setGiveNumber(activityGiveaway.getGiveNumber());
		agtiveModel.setStartDate(activityGiveaway.getStartDate());
		agtiveModel.setEndDate(activityGiveaway.getEndDate());
		agtiveModel.setCheckStock(activityGiveaway.getCheckStock());
		return agtiveModel;
	}

	private Boolean setRedisGiveAway(YgActivityGiveaway activityGiveaway, String type) {
		boolean isExist = false;
		List<ActivityGiveawayModel> list = new ArrayList<ActivityGiveawayModel>();
		List<ActivityGiveawayModel> newlist = new ArrayList<ActivityGiveawayModel>();

		String result = redisDao.get("giveaway_" + activityGiveaway.getSourceCode());
		if (!StringUtils.isEmpty(result)) {

			list = JSON.parseObject(result, new TypeReference<List<ActivityGiveawayModel>>() {
			});

			for (ActivityGiveawayModel model : list) {
				if (type.equals("add")) {// 添加时 一个时间段相同的付款金额 只能存在一个赠品
					if (model.getPayPrice().equals(activityGiveaway.getPayPrice())
							&& model.getEndDate().after(activityGiveaway.getStartDate())) {

						isExist = true;
					}
					newlist.add(model);
				}
				if (type.equals("update")) {// 编辑 只需判断 支付订单金额相同即可
					if (!model.getPayPrice().equals(activityGiveaway.getPayPrice())) {
						newlist.add(model);
					}
				}
			}
		}
		if (!isExist)// 不存在则添加
		{
			newlist.add(copyGiveaway(activityGiveaway));
			redisDao.set("giveaway_" + activityGiveaway.getSourceCode(), JsonUtils.toJson(newlist), 60 * 60 * 1000 * 24
					* 15);// 时间应该计算最大区间

		}

		return isExist;

	}

}
